<?php

class LoginAction extends Action {

	public function _before_index() {
		$greencms_hash=cookie( 'greencms_hash');
	
		if (!empty($greencms_hash)) {
			$user = M( 'User' );
	
			$condition ['sessioncode'] = $greencms_hash;
			$login_res = $user->where($condition)->find();
			if (!empty($login_res)) {
				$_SESSION[C('USER_AUTH_KEY')] = $login_res['user_id'];
				$this->redirect ('Admin/Index/index');
			}
		}
	
	}

	public function index() {
		if (IS_POST) {
			$map = array ();
			$map ['user_login'] = $_POST ['username'];
			$map ['user_status'] = array (
					'gt',
					0 
			);
			import ( 'ORG.Util.RBAC' );
			$authInfo = RBAC::authenticate ( $map );
			
			// 使用用户名、密码和状态的方式进行认证
			if (false === $authInfo) {
				$this->error ( '帐号不存在或已禁用！' );
			} else {
				if ($authInfo ['user_pass'] != md5 ( $_POST ['password'] )) {
					$this->error ( '密码错误或者帐号已禁用' );
				}
				$_SESSION [C ( 'USER_AUTH_KEY' )] = $authInfo ['user_id'];
				if ($authInfo ['user_login'] == 'admin') {
					$_SESSION [C ( 'ADMIN_AUTH_KEY' )] = true;
				}
				//记住我
				if($_POST['remember'] == 1) {
					if($authInfo['sessioncode'] != '') {
						cookie('greencms_hash', $authInfo['sessioncode'], 60 * 60 * 24);
					}
					else if($authInfo['sessioncode'] == '') {
						$user = M( 'User' );
						$condition ['user_id'] = $authInfo['user_id'];
						$sessioncode = md5($user_info['$user_id'].$user_info['user_pass'].time());
						$user-> where($condition)->setField('sessioncode', $sessioncode);
						cookie('greencms_hash', $sessioncode, 60 * 60 * 24);
					}
				}
				// 缓存访问权限
				RBAC::saveAccessList ();
				$this->success ( '登录成功！', U ( "Admin/Index/index" ),false );
			}
			;
		} else {
			$this->display ( 'login' );
		}
	}
	public function forgetpass() {
		
	}
	public function logout() {
		D('Login')->update_hash($_SESSION[C('USER_AUTH_KEY')]);
		cookie('greencms_hash', null);

		session_unset ();
		session_destroy ();
		
		$this->success ( '退出成功！', U ( 'Admin/Login/index' ),false );
		
		
	}
}